<template>
	<view class="app">
		<view class="price-box">
			<text>支付金额</text>
			<text class="price">{{dtsOrder.orderPrice}}</text>
		</view>

		<view class="pay-type-list">

			<view class="type-item b-b" @click="changePayType(1)">
				<text class="icon yticon icon-weixinzhifu"></text>
				<view class="con">
					<text class="tit">微信支付</text>
					<text>推荐使用微信支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == 1' />
					</radio>
				</label>
			</view>
			<view class="type-item b-b" @click="changePayType(2)">
				<text class="icon yticon icon-alipay"></text>
				<view class="con">
					<text class="tit">支付宝支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == 2' />
					</radio>
				</label>
			</view>
			<view class="type-item" @click="changePayType(3)">
				<text class="icon yticon icon-erjiye-yucunkuan"></text>
				<view class="con">
					<text class="tit">预存款支付</text>
					<text>可用余额 ¥198.5</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == 3' />
					</radio>
				</label>
			</view>
		</view>

		<text class="mix-btn" @click="confirm">确认支付</text>
	</view>
</template>

<script>
	import {
		getCreateOrder,
		getQuOrder
	} from '@/config/api/order.js';
	import {
		getDeleted
	} from '@/config/api/cart.js';
	import {
		getPay
	} from '@/config/api/pay.js';
	import { getUseCoupon } from '@/config/api/coupon.js';
	import { mapState } from 'vuex';
	export default {
		data() {
			return {
				payType: 1,
				orderInfo: {},
				payAmount: 0,
				dtsOrder: {

				},
				ids: [],
				// 订单id
				orderId: 0,
				selectedCoupons : []
			};
		},
		computed: {
		    ...mapState(['userInfo'])
		  },
		async onLoad(options) {
			if (options.params) {
				try {
					const orderParams = JSON.parse(decodeURIComponent(options.params));
					console.log('订单数据:', orderParams.orderData);
					console.log('地址信息:', orderParams.addressData);
					console.log('总金额:', orderParams.sumPrice);
					console.log('优惠卷信息:', orderParams.selectedCoupon);
					this.selectedCoupons = orderParams.selectedCoupon;
					console.log(this.selectedCoupons);
					console.log(orderParams.message);

					let dtsOrderGoods = orderParams.orderData.brands;
					let aa = [];
					let ids = [];
					dtsOrderGoods.forEach(function(dtsOrderGoods) {
						dtsOrderGoods.goods.forEach(function(goods) {
							ids.push(
								goods.id
							);
							aa.push({
								brandId: goods.brandId,
								goodsId: goods.goodsId,
								goodsName: goods.goodsName,
								goodsSn: goods.goodsSn,
								productId: goods.productId,
								number: goods.number,
								price: goods.price,
								specifications: goods.specifications,
								picUrl: goods.picUrl,
							});
						})
					})
					console.log("具体商品：" + aa);
					console.log("购物车id" + ids);
					this.ids = encodeURIComponent(JSON.stringify(ids));
					//地址
					let pcaddress = "";
					pcaddress += orderParams.addressData.provinceName.name +
						" " + orderParams.addressData.cityName.name + " " + orderParams.addressData.areaName.name;


					const currDate = new Date();

					// 年月日（8位：YYYYMMDD）
					const yearFull = currDate.getFullYear().toString(); // 4位年
					const month = (currDate.getMonth() + 1).toString().padStart(2, '0'); // 2位月
					const day = currDate.getDate().toString().padStart(2, '0'); // 2位日
					const datePart = `${yearFull}${month}${day}`; // 8位

					// 时分秒毫秒混合值（6位：HHMMSS取后4位 + 毫秒前2位）
					const timeStr =
						`${currDate.getHours().toString().padStart(2, '0')}${currDate.getMinutes().toString().padStart(2, '0')}${currDate.getSeconds().toString().padStart(2, '0')}`; // HHMMSS（6位）
					const timePart = timeStr.slice(-4); // 取后4位（如1435）
					const millisecondPart = currDate.getMilliseconds().toString().padStart(3, '0').slice(0,
						2); // 取毫秒前2位（如95）
					const timeMixPart = `${timePart}${millisecondPart}`; // 4+2=6位

					// 组合为14位唯一编号
					const orderId = `${datePart}${timeMixPart}`; // 8+6=14位
					let dtsOrder = {
						userId: this.userInfo.id,
						orderSn: orderId,
						orderStatus: 101,
						consignee: encodeURIComponent(orderParams.addressData.name), // 收货人
						mobile: encodeURIComponent(orderParams.addressData.mobile), // 电话号码
						address: encodeURIComponent(pcaddress), // 地址
						message: orderParams.message, // 用户留言
						goodsPrice: orderParams.sumPrice, // 商品总费用
						freightPrice: orderParams.freight, // 运费
						couponPrice: orderParams.preferential, // 优惠卷减免
						integralPrice: 0, // 用户积分减免
						grouponPrice: 0, // 团购优惠价减免
						orderPrice: orderParams.actuaPayment, // 订单费用
						actualPrice: 0, // 实付费用
						settlementStatus: 0, // 结算状态
						freightType: 0, // 配送方式
						orderGoods: encodeURIComponent(JSON.stringify(aa)),
					};
					this.dtsOrder = dtsOrder;
					console.log(this.dtsOrder);


					// 其他数据同理...
				} catch (e) {
					console.error('参数解析失败:', e);
					// uni.navigateBack();
				}
			}
		},

		methods: {
			//选择支付方式
			changePayType(type) {
				this.payType = type;
			},
			//确认支付
			confirm: async function() {

				try {
					const res = await getCreateOrder(this.dtsOrder);
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						console.log('成功:', res?.data?.msg || '未知错误');
						this.orderId = res.data.data;
						console.log("订单编号", res.data.data);
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
					const res1 = await getDeleted({
						ids: this.ids
					});
					if (res1 && res1.data && typeof res1.data === 'object' && 'code' in res1.data && res1.data.code ===
						200) {
						console.error('购物车删除成功:', res1?.data?.msg || '未知错误');
					} else {
						console.error('请求失败:', res1?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}


				// uni.showModal({
				// 	title: '确认支付',
				// 	content: '是否确认付款？',
				// 	confirmText: '确认',
				// 	cancelText: '取消',
				// 	success: async (res) => {
				// 		if (res.confirm) { // 只有用户点击确认时才执行支付流程
				// 			try {
				// 				const res1 = await getPay({
				// 					id: this.orderId,
				// 					userId: 1
				// 				});

				// 				console.log("支付参数:", JSON.stringify(res1, null, 2));

				// 				// 发起微信支付
				// 				wx.requestPayment({
				// 					timeStamp: res1.data.data.timeStamp,
				// 					nonceStr: res1.data.data.nonceStr,
				// 					package: res1.data.data.package,
				// 					signType: 'MD5',
				// 					paySign: res1.data.data.paySign,
				// 					success: (payRes) => {
				// 						console.log('支付成功', payRes);
				// 						uni.showToast({
				// 							title: '支付成功',
				// 							icon: 'none',
				// 							duration: 2000
				// 						});

				// 						// 支付成功后的订单状态更新
				// 						this.updateOrderStatus();
				// 					},
				// 					fail: (err) => {
				// 						console.log('支付失败', err);
				// 						uni.showToast({
				// 							title: '支付失败请重新支付',
				// 							icon: 'none',
				// 							duration: 2000
				// 						});
				// 					},
				// 				});
				// 			} catch (error) {
				// 				console.error('获取支付参数失败', error);
				// 				uni.showToast({
				// 					title: '支付初始化失败',
				// 					icon: 'none',
				// 					duration: 2000
				// 				});
				// 			}
				// 		}
				// 	}
				// });



				uni.showModal({
					title: '确认支付',
					content: '是否确认付款？',
					confirmText: '确认',
					cancelText: '取消',
					success: async (res) => {
						//使用了优惠卷
						if (this.selectedCoupons != "" && this.selectedCoupons != null){
							const coupons = await getUseCoupon({
								orderSn : this.dtsOrder.orderSn,
								userId : this.dtsOrder.userId,
								id : this.selectedCoupons.id
							});
							
							if (coupons && coupons.data && typeof coupons.data ===
								'object' && 'code' in coupons
								.data && coupons.data.code === 200) {
								console.log('成功:', coupons?.data?.msg || '未知错误');
							} else {
								console.error('请求失败:', coupons?.data?.msg ||
									'未知错误');
							}
						}
						if (res.confirm) {
							const res1 = await getPay({
								id: this.orderId,
								userId: this.userInfo.id
							});
							
							console.log(JSON.stringify(res1, null, 2));
							wx.requestPayment({
								timeStamp: res1.data.data.timeStamp,
								nonceStr: res1.data.data.nonceStr,
								package: res1.data.data.package,
								signType: 'MD5',
								paySign: res1.data.data.paySign,
								success: async (res) => {
									console.log('支付成功', res);
									uni.showToast({
										title: '支付成功',
										icon: 'none',
										duration: 2000
									});
									// console.log(JSON.stringify(res1, null, 2));
									// console.log(JSON.stringify(res, null, 2));
									// 可以在这里添加支付成功后的逻辑，如跳转到订单详情页等
									if (res1 && res1.data && typeof res1
										.data === 'object' && 'code' in
										res1.data && res1.data.code ===
										200) {
										try {
											// 订单状态、实付价格、付款时间、更新时间
											const res = await getQuOrder({
												id: this.orderId,
												orderStatus: 201,
												actualPrice: this.dtsOrder.orderPrice,
												payId: 159263,
											});
											if (res && res.data && typeof res.data ===
												'object' && 'code' in res
												.data && res.data.code === 200) {
												console.log('成功:', res?.data?.msg || '未知错误');
											} else {
												console.error('请求失败:', res?.data?.msg ||
													'未知错误');
											}
											
											
											uni.redirectTo({
												url: '/pages/money/paySuccess?status=成功'
											})
										} catch (error) {
											console.error('接口异常:', error)
											this.$message.error('数据加载失败')
										}
									}
								},
								fail: (err) => {
									console.log('支付失败', err);
									// 可以在这里添加支付失败后的逻辑，如提示用户重新支付等
									uni.showToast({
										title: '支付失败请重新支付',
										icon: 'none',
										duration: 2000
									});
									uni.redirectTo({
										url: '/pages/money/paySuccess?status=失败'
									})
								},
							});
						} else if (res.cancel) {
							console.log('用户取消支付');
							uni.showToast({
								title: '已取消支付',
								icon: 'none',
								duration: 2000
							});
							uni.redirectTo({
								url: '/pages/money/paySuccess?status=失败'
							})
						}
					}
				});

			},
		}
	}
</script>

<style lang='scss'>
	.app {
		width: 100%;
	}

	.price-box {
		background-color: #fff;
		height: 265upx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28upx;
		color: #909399;

		.price {
			font-size: 50upx;
			color: #303133;
			margin-top: 12upx;

			&:before {
				content: '￥';
				font-size: 40upx;
			}
		}
	}

	.pay-type-list {
		margin-top: 20upx;
		background-color: #fff;
		padding-left: 60upx;

		.type-item {
			height: 120upx;
			padding: 20upx 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-right: 60upx;
			font-size: 30upx;
			position: relative;
		}

		.icon {
			width: 100upx;
			font-size: 52upx;
		}

		.icon-erjiye-yucunkuan {
			color: #fe8e2e;
		}

		.icon-weixinzhifu {
			color: #36cb59;
		}

		.icon-alipay {
			color: #01aaef;
		}

		.tit {
			font-size: $font-lg;
			color: $font-color-dark;
			margin-bottom: 4upx;
		}

		.con {
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-sm;
			color: $font-color-light;
		}
	}

	.mix-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 630upx;
		height: 80upx;
		margin: 80upx auto 30upx;
		font-size: $font-lg;
		color: #fff;
		background-color: $base-color;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	}
</style>